package com.md.drcs.dicom.dao;

import com.md.common.utils.dao.MyMapper;
import com.md.drcs.dicom.dto.MessageDTO;
import com.md.drcs.dicom.entity.ImMessageEntity;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface ImMessageDao extends MyMapper<ImMessageEntity> {

    /**
     * 更新单条消息为指定状态
     * @param id 消息ID
     * @param status 消息状态
     */
    @Update("update m_im_message set `status` = #{status} where id = #{id}")
    void updateStatus(@Param("id") Integer id, @Param("status") Integer status);

    /**
     * 根据接收人将所有消息更新为已读状态
     * @param toUserId 接收人ID
     */
    @Update("update m_im_message set `status` = 1 where `status` = 0 and to_user_id = #{toUserId} and from_user_id = #{fromUserId}")
    void updateToReaded(@Param("toUserId") Integer toUserId, @Param("fromUserId") Integer fromUserId);

    /**
     * 根据接收人获取指定发送人所有未读消息
     * @param toUserId 接收人ID
     * @param fromUserId 发送人ID
     * @return
     */
    @Select("select * from m_im_message where `status` = 0 and to_user_id = #{toUserId} and from_user_id = #{fromUserId} order by id asc")
    List<MessageDTO> findUnread(@Param("toUserId") Integer toUserId, @Param("fromUserId") Integer fromUserId);

    /**
     * 根据接收人获取指定发送人的最近200条已读消息
     * @param toUserId
     * @param fromUserId
     * @return
     */
    @Select("select * from m_im_message" +
            " where " +
            " (`status` = 1" +
            " and to_user_id = #{toUserId}" +
            " and from_user_id = #{fromUserId})" +
            " or" +
            " (to_user_id = #{fromUserId}" +
            " and from_user_id = #{toUserId})" +
            " order by id asc limit 0, 200")
    List<MessageDTO> findNestReadedMessage(@Param("toUserId") Integer toUserId, @Param("fromUserId") Integer fromUserId);

    /**
     * 根据接收人获取未读消息数量
     * @param toUserId
     * @return
     */
    @Select("select count(0) from m_im_message where `status` = 0 and to_user_id = #{toUserId}")
    Integer getUnreadCount(Integer toUserId);

    @Select("select count(0) from m_im_message where `status` = 0 and to_user_id = #{toUserId} and from_user_id = #{fromUserId}")
    Integer getUnreadCountByFromUserId(@Param("toUserId") Integer toUserId, @Param("fromUserId") Integer fromUserId);

    /**
     * 获取最近3天消息记录中与指定用户相关的其他用户信息
     * @param toUserId
     * @return
     */
    @Select("SELECT DISTINCT from_user_id, to_user_id FROM m_im_message WHERE (from_user_id = #{toUserId} or to_user_id = #{toUserId}) and create_time >= DATE_SUB(CURDATE(), INTERVAL 3 DAY)")
    List<ImMessageEntity> findLastThreeDaysChatUsers(Integer toUserId);
}
